package com.candy.candymessagerpc.config;

import com.candy.candycommon.Event.ExceptionEvent;
import com.candy.candycommon.Event.ExceptionEventListener;
import com.candy.candycommon.enums.MsgFormatEnum;
import com.candy.candycommon.utils.StackTraceUtils;
import com.candy.candymessagerpc.bean.Message;
import com.candy.candymessagerpc.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/6/5 15:12
 * @Description 默认异常处理发送器
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "rpc", name = "message.sendException.enable", havingValue = "true", matchIfMissing = false)
public class SendExceptionEventMsgConfig {

    @Resource
    MessageService messageService;

    @Resource
    RpcMessageProperty rpcMessageProperty;

    @Bean
    public ExceptionEventListener exceptionEventListener() {
        return new ExceptionEventListener(event -> {
            log.error("消息服务监听到异常消息：{}", event);
            if (rpcMessageProperty.getSendException().getEnable()) {
                Message message = new Message(rpcMessageProperty.getSendException().getMsgTypeEnum().getCode(), Optional.ofNullable(event).map(ev -> {
                    return ev instanceof ExceptionEvent ?
                            "【异常通知】" + (MsgFormatEnum.SIMPLE.equals(rpcMessageProperty.getSendException().getMsgFormat()) ?
                                    ((Exception) (((ExceptionEvent) ev).getData())).getMessage()
                                    : StackTraceUtils.getStackTrace((Exception) (((ExceptionEvent) ev).getData())))
                            : "";
                }).orElse(""));
                messageService.send(message);
            }
        });
    }

}
